package com.JingYan.service.impl;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.filter.ThresholdFilter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.rolling.RollingFileAppender;

import com.JingYan.service.LogbacksService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author DongJiaQi
 * @create 2022/12/9 11:00
 * @Description:
 */
@Slf4j
@Service
public class LogbacksServiceImpl implements LogbacksService {
    @Override
    public boolean setFileDebug(int type) {
        LoggerContext loggerContext = ((Logger) log).getLoggerContext();
        Logger root = loggerContext.getLogger("root");
        RollingFileAppender<ILoggingEvent> file_debug = (RollingFileAppender<ILoggingEvent>) root.getAppender("file_debug");
        //过滤器无法直接修改,重新创建一个过滤器
        //ThresholdFilter tf = new ThresholdFilter();
        //tf.setContext(loggerContext);
        List<Filter<ILoggingEvent>> copyOfAttachedFiltersList = file_debug.getCopyOfAttachedFiltersList();
        //清空过滤器
        file_debug.clearAllFilters();
        for (Filter<ILoggingEvent> iLoggingEventFilter : copyOfAttachedFiltersList) {
            if (iLoggingEventFilter instanceof ThresholdFilter){
                ThresholdFilter tf = (ThresholdFilter) iLoggingEventFilter;
                if (type ==0){
                    tf.setLevel(Level.OFF.levelStr);
                }else if(type == 2){
                    tf.setLevel(Level.DEBUG.levelStr);
                }
            }
            //放入过滤器
            file_debug.addFilter(iLoggingEventFilter);
        }

        return true;
    }
}
